/**
 *
 */
package com.ayf.payment.game.api.controller.eqb;

import com.swwx.charm.commons.lang.utils.LogPortal;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.*;

/**
 * @author chen_xi
 * 验证签名
 */
public class SafeVerify {

    public Map<String, Object> checkPass(String uniqueId, HttpServletRequest request, String appSecret) throws UnsupportedEncodingException {
        String signture = request.getHeader("X-Tsign-Open-SIGNATURE");
        //1. 获取时间戳的字节流
        String timestamp = request.getHeader("X-Tsign-Open-TIMESTAMP");
//		String content_type  =request
        //2. 获取query请求字符串
        String requestQuery = getRequestQueryStr(uniqueId, request);
        //3. 获取body的数据
        String rbody = getRequestBody(request, "UTF-8");
        //4、按照规则进行加密
        String signdata = timestamp + requestQuery + rbody;
        LogPortal.info("[{}]签名原数据为:[{}]", uniqueId, signdata);
        String mySignature = DigestHelper.getSignature(uniqueId,signdata, appSecret, "HmacSHA256", "UTF-8");
        LogPortal.info("[{}]加密出来的签名值[{}]", uniqueId, mySignature);
        LogPortal.info("[{}]header里面的签名值[{}]", uniqueId, signture);
        if (mySignature.equals(signture)) {
            LogPortal.info("[{}]校验通过", uniqueId);
            Map<String,Object> map=new HashMap<>();
            map.put("signStatus","true");
            map.put("body",rbody);
            return map;

        } else {
            LogPortal.info("[{}]校验失败", uniqueId);
            Map<String,Object> map=new HashMap<>();
            map.put("signStatus","false");
            map.put("body",rbody);
            return map;
        }

    }

    /**
     * 获取请求body
     * @param request
     * @param encoding
     * @return
     */
    private String getRequestBody(HttpServletRequest request, String encoding) {
        // 请求内容RequestBody
        String reqBody = null;
        int contentLength = request.getContentLength();
        if (contentLength < 0) {
            return null;
        }
        byte buffer[] = new byte[contentLength];
        try {
            for (int i = 0; i < contentLength; ) {
                int readlen = request.getInputStream().read(buffer, i, contentLength - i);
                if (readlen == -1) {
                    break;
                }
                i += readlen;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            reqBody = new String(buffer, encoding);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return reqBody;
    }

    /**
     * 获取query请求字符串
     * @param request
     * @return
     */
    private String getRequestQueryStr(String uniqueId, HttpServletRequest request) {
        //对 Query 参数按照字典对 Key 进行排序后,按照value1+value2方法拼接
        //转换一下数据类型并排序
        List<String> req_List = new ArrayList();
        Enumeration<String> reqEnu = request.getParameterNames();
        while (reqEnu.hasMoreElements()) {
            req_List.add(reqEnu.nextElement());
        }
        Collections.sort(req_List);
        StringBuilder requestQuery = new StringBuilder();
        for (String key : req_List) {
            String value = request.getParameter(key);
            requestQuery.append(value == null ? "" : value);
        }
        LogPortal.info("[{}]获取的query请求字符串是[{}]", uniqueId, requestQuery.toString());
        return requestQuery.toString();
    }

}
